﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SerialPortTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            DrawingControl.SuspendDrawing(this.richTextBox1);

            this.richTextBox1.Text += e.KeyChar;
            this.richTextBox1.SelectionStart = this.richTextBox1.Text.Length;
            this.richTextBox1.ScrollToCaret();
            DrawingControl.ResumeDrawing(this.richTextBox1);
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            SetDoubleBuffered(this.richTextBox1);
            // this.serialPort1.Open();
            Debug.WriteLine("Loaded");
        }

        private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string data = this.serialPort1.ReadExisting();
            this.richTextBox1.Invoke(new Action(() => this.richTextBox1.Text += data));
        }

        public static void SetDoubleBuffered(System.Windows.Forms.Control c)
        {
            //Taxes: Remote Desktop Connection and painting
            //http://blogs.msdn.com/oldnewthing/archive/2006/01/03/508694.aspx
            if (System.Windows.Forms.SystemInformation.TerminalServerSession)
                return;

            System.Reflection.PropertyInfo aProp =
                  typeof(System.Windows.Forms.Control).GetProperty(
                        "DoubleBuffered",
                        System.Reflection.BindingFlags.NonPublic |
                        System.Reflection.BindingFlags.Instance);

            aProp.SetValue(c, true, null);
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.serialPort1.Close();
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            Debug.WriteLine("Shown");
        }
    }
}
